package goodroommate.ui.account;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import goodroommate.domain.User;
import goodroommate.exception.DatabaseException;
import goodroommate.exception.ItemAlreadyExistsException;
import goodroommate.service.IUserService;
import goodroommate.service.impl.UserService;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/Account/Register")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	IUserService userService=new UserService();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("register.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String action=request.getParameter("action");
		if(!action.equals("register"))
			response.sendError(403);
		else
			doRegister(request,response);
	}
	protected void doRegister(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		
		if(username==null||"".equals(username)
		||password==null||"".equals(password)){
			response.sendError(403);
			return ;
		}
		
		if(username.length()<5){
			response.sendError(403);
			return ;
		}
		
		if(password.length()<6){
			response.sendError(403);
			return ;
		}
		int errorCode=0;
		User user=null;
		try{
			user=userService.register(username, password);
		}catch(ItemAlreadyExistsException e){
			errorCode=1;
		}catch(DatabaseException e){
			response.sendError(500);
			return;
		}
		
		if(errorCode==0){
			HttpSession session=request.getSession();
			session.setAttribute("user", user);
			response.sendRedirect(request.getContextPath()+"/Homepage");
			return;
		}
		
		request.setAttribute("errorCode", errorCode);
		request.getRequestDispatcher("register.jsp").forward(request, response);
		
	}

}
